<template>
  <div class="study">
    <div class="tree-top" >
      <div class="left">
        <el-input
            v-model="keyword"
            placeholder="清空输入框取消查询"
            style="width: 60%;margin-right: 1vw"
            clearable
            @change="clearInput"
        />
        <el-button
            @click="onSearch"
        >
          搜索
        </el-button>
      </div>
      <div class="right">
        <el-button
            v-if="user.root === 0 || user.role === 6"
            @click="showUpload"
            type="primary"
        >
          上传
        </el-button>
      </div>
    </div>
    <el-table
        :data="tableData"
        stripe
        style="width: 95%;height: 92vh;background-color: rgba(255,255,255,.5);margin: 0 auto"
        border
        max-height="92vh"
        empty-text="暂无数据"
    >
      <el-table-column
          fixed
          label="ID"
          width="150"
          align="center"
          type="index"
      />
      <el-table-column
          prop="name"
          label="标题"
          align="center"
          width="700"
      />
      <!--<el-table-column-->
      <!--    label="标题"-->
      <!--    align="center"-->
      <!--    width="700"-->
      <!--&gt;-->
      <!--  <template #default="row">-->
      <!--    <el-tag>-->
      <!--      {{processSealFileJSON(row.file).ext}}-->
      <!--    </el-tag>-->
      <!--  </template>-->
      <!--</el-table-column>-->
      <el-table-column
          prop="uploaderName"
          label="上传人"
          align="center"
          width="150"
      />
      <el-table-column
          prop="uploaderName"
          label="操作"
          align="center"
      >
        <template #default="{row}">
          <el-button
              v-if="row.file"
              @click="previewFile(row.id,row)"
          >
            预览
          </el-button>
          <el-button
              v-if="row.file"
              @click="downloadFile(row.id,row.uploaderName,row.file,row.name)"
          >
            下载
          </el-button>
          <el-button
              @click="showUpdate"
              v-if="user.root === 0 || user.role === 6"
          >
            编辑
          </el-button>
          <el-button
              @click="del(row.id)"
              v-if="user.root === 0 || user.role === 6"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
        v-model="editDialogVisible"
        title="修改"
        width="40vw"
        :before-close="handleCloseUpdate"
        :close-on-click-modal="false"
    >
      <el-form
          ref="ruleFormRef"
          style="max-width: 100%"
          :model="edit"
          label-width="auto"
          class="demo-ruleForm"
          size="default"
          status-icon
      >
        <el-form-item label="标题" class="el-form-items">
          <el-input v-model="edit.name" style="width: 100%" placeholder="填写名称"/>
        </el-form-item>
        <div class="btn-box" style="margin-top: 3vh;">
          <el-button type="primary" @click="onUpdate">
            提交
          </el-button>
        </div>
      </el-form>
    </el-dialog>


    <el-dialog
        v-model="uploadDialogVisible"
        title="上传"
        width="40vw"
        :before-close="handleCloseUpload"
        :close-on-click-modal="false"
    >
      <el-form
          ref="ruleFormRef"
          style="max-width: 100%"
          :model="edit"
          label-width="auto"
          class="demo-ruleForm"
          size="default"
          status-icon
      >
        <el-form-item label="标题" class="el-form-items">
          <el-input v-model="uploadForm.name" style="width: 100%" placeholder="填写名称"/>
        </el-form-item>
        <el-form-item label="附件" class="el-form-items upload-items">
          <el-upload
              v-model:file-list="uploadForm.file"
              class="upload-demo"
              :action="createURL"
              multiple
              :limit="1"
              :on-exceed="handleExceed"
              :on-change="handleSealFileChange"
              :on-success="handleSealFileSuccess"
              :auto-upload="false"
          >
            <!--style="    height: 90%;display: flex;flex-direction: column;"-->
            <el-button size="small">点击上传</el-button>
            <div class="el-upload__text" style="font-family: dingding">
              单次仅可上传一个文件
            </div>
          </el-upload>
        </el-form-item>
        <div class="btn-box" style="margin-top: 3vh;">
          <el-button type="primary" @click="onUpload">
            提交
          </el-button>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup>
import {ElButton, ElDialog, ElForm, ElInput, ElTable, ElTableColumn, ElUpload} from "element-plus"
import {onMounted, reactive, ref} from "vue"
import {deleteFile, downloadStudy, getAll, search, searchStudy, update, updateStudy, uploadStudy} from "@/api/Study"
import {createMsg, getUserInfo, isPDF, processSealFileJSON} from "@/lib/utils"
import {createURL, previewURL, previewYRL, resubmitURL} from "@/api/http"
import {download, searchByWord} from "@/api/OA/Approve"
import bgc from "@/assets/images/study.jpg"

let user = getUserInfo()
const editDialogVisible = ref(false)
const uploadDialogVisible = ref(false)
const keyword = ref('')
const tableData = ref([])
const file = ref([])
const edit = reactive({
  name:'',
})

let uploadForm = reactive({
  name:'',
  file:[]
})

onMounted(()=>{
  getList()
})

const getList = async () => {
  try {
    tableData.value = []
    const {data:res} = await getAll()
    if (res.code === 200){
      tableData.value = res.data
    } else if (res.code === 201){
      tableData.value = []
    } else {
      return createMsg('未查询到数据','info',true)
    }
  } catch (e) {
    console.log(e)
  }
}

const onSearch = async () => {
  try {
    if (keyword.value){
      const {data:res} = await searchStudy(user.id,keyword.value)
      console.log(res)
      if (res.code === 200){
        tableData.value = []
        tableData.value = res.data
      } else if (res.code === 201){
        tableData.value = []
      } else {
        return createMsg('未查询到相关信息','info',true)
      }
    } else {
      tableData.value = []
      await getApproveList()
    }
  } catch (e) {
    console.log(e)
  }
}

const previewFile = async (id,row) => {
  if (!isPDF(row)) return createMsg('仅pdf文件支持在线预览','info',true)
  await window.open(`${previewURL}/previewSt?id=${id}`)
}

const downloadFile = async (id,uploaderName,file,name) => {
  try {
    const res = await downloadStudy(id)
    const type = processSealFileJSON(file)
    // 创建一个新的 URL 对象，并生成一个下载链接
    const url = window.URL.createObjectURL(new Blob([res.data],
        ));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', `${name}.${type.ext}`); // 设置下载的文件名
    link.style.display = 'none' // 隐藏元素
    document.body.appendChild(link);
    link.click()
    // 清理 DOM 和释放 URL 对象
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
  } catch (e) {
    console.log(e)
  }
}

let target
const showUpdate = (id) => {
  target = id
  editDialogVisible.value = true
}

const onUpdate = async () => {
  try {
    const {data:res} = await updateStudy(edit.name,target)
    if (res.code === 200){
      edit.name = ''
      await getList()
      editDialogVisible.value = false
      target = null
      createMsg('操作成功!','success',true)
    } else {
      edit.name = ''
      editDialogVisible.value = false
      target = null
      createMsg('操作失败!','info',true)
    }
  } catch (e) {
    console.log(e)
  }
}

const del = async (id) => {
  try {
    const con = window.confirm('确认删除？')
    if (con){
      const {data:res} = await deleteFile(id)
      if (res.code === 200){
        await getList()
        createMsg('操作成功!','success',true)
      } else {
        createMsg('操作失败!','info',true)
      }
    }
  } catch (e) {
    console.log(e)
  }
}



// 当超出限制时，执行的钩子函数
const handleExceed = () => {
  createMsg('单次只能上传一个文件','warning')
}

const handleSealFileChange = (e) => {
  file.value = []
  console.log(file,e.raw,'file.raw')
  file.value.push(e.raw)
}

//
const handleSealFileSuccess = (file) => {
  console.log(file,'s')
}

const showUpload = async () => {
  try {
    uploadDialogVisible.value = true
  } catch (e) {
    console.log(e)
  }
}

const onUpload = async () => {
  try {
    if (!uploadForm.name || !file.value.length){
      return createMsg('请完整填写信息','info',true)
    }
    let form = new FormData()
    form.append("userId", user.id);
    form.append("name", uploadForm.name);
    form.append("file",file.value[0])
    console.log(user.id,uploadForm.name,file.value[0])
    const {data:res} = await uploadStudy(form)
    if (res.code === 200){
      await getList()
      createMsg('上传成功!','success',true)
      edit.name = ''
      edit.file = []
      uploadDialogVisible.value = false
    }
  } catch (e) {
    console.log(e)
  }
}
const handleCloseUpload = () => {
  uploadForm.name = ''
  uploadForm.file = []
  uploadDialogVisible.value = false
  file.value = []
}

const handleCloseUpdate = () => {
  editDialogVisible.value = false
  edit.name = ''
}

const clearInput = () => {
  if (!keyword.value) getList()
}
</script>

<style scoped lang="less">
.study{
  margin-left: 7vw;
  background-image: url(@/assets/images/study.jpg);
  background-size: cover;
  margin-top: -1vh;
  height: 100vh;
}
.tree-top{
  justify-content: space-between;
  padding-right: 5vw;
  margin: 2vh 0;
  display: flex;
  box-sizing: border-box;
  .left{
    width: 35%;
  }
}


:deep(.el-table){
  background:rgba(255,255,255,.3) !important;
}
:deep(.el-table_expanded-cell){
  background:rgba(255,255,255,.3) !important;
}
:deep(.el-table th){
  background:rgba(255,255,255,.3) !important;
}
:deep(.el-table tr){
  background:rgba(255,255,255,.3) !important;
}
:deep(.el-table td){
  background:rgba(255,255,255,.3) !important;
}
:deep(.el-table){
  --el-table-border-color: rgba(227, 227, 227);
  --el-table-row-hover-bg-color: transparent;
  --el-table-current-row-bg-color: transparent;
  --el-table-header-bg-color: transparent;
  --el-table-bg-color: transparent;
  --el-table-tr-bg-color: transparent;
  --el-table-expanded-cell-bg-color: transparent;
  .el-table--enable-row-transition{
    background:rgba(255,255,255,.3) !important;

  }
}
</style>
